﻿using Ldt.CommonCapacitySupport.Business.Model;
using Ldt.DataEngine.LogHandle;
using LdtDataEngin.ModuleDetail.BaseModule.MultiFack;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using LdtJudge.DataEngine.Model.XMLConfigModel.OptimizeConfigModel;
using LdtJudge.DataEngine.Model.XMLConfigModel.OptimzeMode;
using LdtJudge.DataEngine.Model.XMLConfigModel.SameNodeConfigModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using static Ldt.DataEngine.LogHandle.LogHandle;

namespace Ldt.CommonCapacitySupport.Business
{
    public class ComparePersonElementHandle
    {
        private LogShow _uishow;
        private GetSysCaseCause sysCaseCause = new GetSysCaseCause();
        /// <summary>
        /// 有异议要素
        /// </summary>
        private Dictionary<Tuple<string, string>, XmlNode> differenceList = new Dictionary<Tuple<string, string>, XmlNode>();

        /// <summary>
        /// 日志显示
        /// </summary>
        public LogShow LogShow
        {
            get { return DoSetLog; }
            set { _uishow = value; }
        }

        /// <summary>
        /// 构造
        /// </summary>
        public ComparePersonElementHandle()
        {
        }

        /// <summary>
        /// 比对要素
        /// </summary>
        /// <param name="model">比对模型，包含了要比对的要素信息</param>
        /// <returns></returns>
        public ComparePersonElementReturnModel CompareElement(ComparePersonElementModel model)
        {
            #region 实例化返回结果
            ComparePersonElementReturnModel re = new ComparePersonElementReturnModel();
            re.AppCode = model.AppCode;
            re.CaseCauseID = model.CaseCauseID;
            re.CaseID = model.CaseID;
            re.CaseType = model.CaseType;
            re.OutRelateID = model.OutRelateID;
            re.resultList = new List<CompareResultModle>();
            #endregion

            #region 处理xml，节点添加ID
            for (int i = 0; i < model.PersonElements.Count; i++)
            {
                string xmlContent = HttpHelp.DeCodeBase64new(65001, model.PersonElements[i].Content);
                xmlContent = XmlNodeAddIDAttribute(xmlContent);
                model.PersonElements[i].Content = HttpHelp.EnDataBase64(xmlContent);
            }
            #endregion
            try
            {
                //认定要素
                XmlDocument confirmdocument = new XmlDocument();

                #region 获取案由模板结构
                string strxmlTemplate = sysCaseCause.GetModel(model.CaseCauseID).ElementXML;
                CaseCauseModel caseCauseModel = sysCaseCause.GetModel(model.CaseCauseID);
                XmlDocument xmlDocumentTemplate = new XmlDocument();
                xmlDocumentTemplate.LoadXml(strxmlTemplate);
                #endregion

                #region  获取同节点判定配置
                string xmlpath = @"config//moduleconfig//commonconfig//generalconfig//samenodeconfig//" + model.CaseType + "_" + model.CaseCauseID + ".xml";
                SameNodeConfig xmlConfigModel = LoadXmlSerializableConfig<SameNodeConfig>(xmlpath);
                #endregion

                #region 重新组装人员要素信息并执行比对
                Dictionary<Tuple<string, string>, XmlNode> personxmlNode = new Dictionary<Tuple<string, string>, XmlNode>();
                // 认定要素结果集合
                List<CompareResultModle> affirmedResultList = new List<CompareResultModle>();
                // 待认定要素结果集合
                List<CompareResultModle> waitAffirmResultList = new List<CompareResultModle>();
                // 有异议要素结果集合
                List<CompareResultModle> dissentResultList = new List<CompareResultModle>();

                #region 1.先取到待认定的要素集合执行比对，得到认定、有异议、最终待认定的要素
                List<PersonElementModel> waitAffirmElement = model.PersonElements.Where(a => a.ElementState == 0).ToList();
                // 认定要素的人员列表
                List<PersonBaseInfo> personBaseInfoList = new List<PersonBaseInfo>();
                foreach (IGrouping<int, PersonElementModel> item in waitAffirmElement.GroupBy(b => b.ElementType))
                {
                    #region 1.1根据要素类型获取模板结构
                    XmlNode nodetemplate = null;
                    switch (item.Key)
                    {
                        case 1:
                            nodetemplate = xmlDocumentTemplate.SelectSingleNode("//诉请要素");
                            break;
                        case 2:
                            nodetemplate = xmlDocumentTemplate.SelectSingleNode("//事实要素");
                            break;
                        case 3:
                            nodetemplate = xmlDocumentTemplate.SelectSingleNode("//诉请要素");
                            break;
                    }
                    #endregion

                    #region  1.2.组装人员要素信息
                    List<PersonElementModel> suitNoAffirmElement = item.ToList<PersonElementModel>();
                    foreach (PersonElementModel personElement in suitNoAffirmElement)
                    {
                        Tuple<string, string> tuplekey = new Tuple<string, string>(personElement.PersonName, personElement.SuitDegreeID);
                        XmlDocument xmlTemp = new XmlDocument();
                        xmlTemp.LoadXml(HttpHelp.DeCodeBase64new(65001, personElement.Content));
                        personxmlNode.Add(tuplekey, xmlTemp);

                        PersonBaseInfo personBaseInfo = new PersonBaseInfo();
                        personBaseInfo.PersonName = personElement.PersonName;
                        personBaseInfo.SuitDegreeID = personElement.SuitDegreeID;
                        personBaseInfoList.Add(personBaseInfo);
                    }
                    #endregion

                    #region 1.3.比对认定要素
                    MultiFactIntersect multiFactinter = new MultiFactIntersect() { caseCauseModel = caseCauseModel };
                    multiFactinter.dataContext = new DataContext(new DataLayerSysStores(), new DyData_Analysis(), new InteractiveShowClass());
                    multiFactinter.dataContext.InteractiveShow.LogShow = new LogShow(LogShow);
                    string confirmxml = multiFactinter.MultiFactHandleCommon(nodetemplate, personxmlNode, xmlConfigModel.xmllable.ToList(), MultiFactBase.SameNodeHandleType.b);
                    if (!string.IsNullOrEmpty(confirmxml))
                        confirmdocument.LoadXml(confirmxml);
                    // 3.1 存认定要素
                    CompareResultModle resultModel = new CompareResultModle();
                    resultModel.ElementState = 1;
                    resultModel.ElementType = item.Key;
                    resultModel.PersonInfo = personBaseInfoList;
                    resultModel.ElementContent = HttpHelp.EnDataBase64(confirmxml);
                    affirmedResultList.Add(resultModel);
                    #endregion

                    #region 1.4.比对有异议要素
                    MultiFactBase multiFactexc = new MultiFactDifference() { caseCauseModel = caseCauseModel }; ;
                    multiFactexc.dataContext = new DataContext(new DataLayerSysStores(), new DyData_Analysis(), new InteractiveShowClass());
                    multiFactexc.dataContext.InteractiveShow.LogShow = new LogShow(LogShow);
                    multiFactexc.MultiFactHandleCommon(nodetemplate, personxmlNode, xmlConfigModel.xmllable.ToList(), MultiFactBase.SameNodeHandleType.b);
                    differenceList = (multiFactexc as MultiFactDifference).DifferenceList;
                    Dictionary<Tuple<string, string>, XmlNode> differElements = (multiFactexc as MultiFactDifference).ptopDifferList;
                    //4.1保存结果数据
                    CompareResultModle loopresultModel = new CompareResultModle();
                    loopresultModel.ElementState = 2;
                    loopresultModel.ElementType = item.Key;
                    loopresultModel.PersonInfo = new List<List<PersonBaseInfo>>();

                    var diffkeys = differElements.Keys.ToList();

                    while (diffkeys.Count > 0)
                    {
                        Tuple<string, string> tuppersion = diffkeys[0];

                        Tuple<string, string> tuppersion2 = diffkeys.FirstOrDefault(ke => ke.Item1 == tuppersion.Item2 && ke.Item2 == tuppersion.Item1);

                        if (tuppersion2 != null)
                        {
                            List<PersonBaseInfo> persons = new List<PersonBaseInfo>();
                            PersonBaseInfo person = new PersonBaseInfo();
                            person.PersonName = tuppersion.Item1.Split('-')[0];
                            person.SuitDegreeID = tuppersion.Item1.Split('-')[1];
                            person.PersonElementContent = HttpHelp.EnDataBase64(differElements[tuppersion].OuterXml);
                            persons.Add(person);

                            PersonBaseInfo person2 = new PersonBaseInfo();
                            person2.PersonName = tuppersion2.Item1.Split('-')[0];
                            person2.SuitDegreeID = tuppersion2.Item1.Split('-')[1];
                            person2.PersonElementContent = HttpHelp.EnDataBase64(differElements[tuppersion2].OuterXml);
                            persons.Add(person2);

                            loopresultModel.PersonInfo.Add(persons);
                        }

                        diffkeys.Remove(tuppersion);
                        diffkeys.Remove(tuppersion2);

                    }
                    dissentResultList.Add(loopresultModel);
                    #endregion

                    #region 1.5.比对待认定要素
                    MultiFactUnConfirm factUnConfirm = new MultiFactUnConfirm() { caseCauseModel = caseCauseModel };
                    factUnConfirm.dataContext = new DataContext(new DataLayerSysStores(), new DyData_Analysis(), new InteractiveShowClass());
                    factUnConfirm.dataContext.InteractiveShow.LogShow = new LogShow(LogShow); ;
                    factUnConfirm.ConfirmNode = confirmdocument;
                    factUnConfirm.Personxml = differenceList;
                    factUnConfirm.MultiFactHandleCommon(nodetemplate, personxmlNode, xmlConfigModel.xmllable.ToList(), MultiFactBase.SameNodeHandleType.b);

                    //5.1存放结果
                    foreach (var unperson in factUnConfirm.Unpersonxml)
                    {
                        PersonBaseInfo person = new PersonBaseInfo();
                        person.PersonName = unperson.Key.Item2;
                        person.SuitDegreeID = unperson.Key.Item1;
                        CompareResultModle wresultModel = new CompareResultModle();
                        wresultModel.ElementState = 0;
                        wresultModel.ElementType = item.Key;
                        wresultModel.PersonInfo = new List<PersonBaseInfo>();
                        wresultModel.PersonInfo.Add(person);
                        wresultModel.ElementContent = HttpHelp.EnDataBase64(unperson.Value.OuterXml);
                        waitAffirmResultList.Add(wresultModel);
                    }
                    #endregion
                }
                #endregion

                #region 2.取到入参中已认定的要素集合，将其追加到上一步的已认定结果集中
                List<PersonElementModel> affirmedElement = model.PersonElements.Where(a => a.ElementState == 1).ToList();
                foreach (var item in affirmedElement)
                {
                    CompareResultModle resultModel = new CompareResultModle();
                    resultModel.ElementState = 1;
                    resultModel.ElementType = item.ElementType;
                    resultModel.PersonInfo = personBaseInfoList;
                    resultModel.ElementContent = HttpHelp.EnDataBase64(item.Content);
                    affirmedResultList.Add(resultModel);
                }
                #endregion

                #region 3.取到入参中有异议的要素集合，将其追加到1的有异议结果集中
                List<PersonElementModel> dissentElement = model.PersonElements.Where(a => a.ElementState == 2).ToList();
                foreach (var item in dissentElement)
                {
                    CompareResultModle resultModel = new CompareResultModle();
                    resultModel.ElementState = 2;
                    resultModel.ElementType = item.ElementType;
                    resultModel.PersonInfo = new List<PersonBaseInfo>();
                    resultModel.PersonInfo.Add(new PersonBaseInfo() { PersonName = item.PersonName, SuitDegreeID = item.SuitDegreeID });
                    resultModel.ElementContent = HttpHelp.EnDataBase64(item.Content);
                    dissentResultList.Add(resultModel);
                }
                #endregion

                #region 4.将结果集添加到返回结构中
                re.resultList.AddRange(affirmedResultList);
                re.resultList.AddRange(waitAffirmResultList);
                re.resultList.AddRange(dissentResultList);
                #endregion
                #endregion
            }
            catch (Exception ex)
            {
                LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, "CompareElement异常" + ex.Message);
            }
            return re;
        }

        /// <summary>
        /// 合并要素结构
        /// </summary>
        /// <param name="model">合并信息</param>
        /// <returns></returns>
        public MergeElementResultModel MergerElement(MergeElementModel model)
        {
            #region 实例化结果集合
            MergeElementResultModel re = new MergeElementResultModel();
            re.appcode = model.AppCode;
            re.casecauseid = model.CaseCauseID;
            re.casetype = model.CaseType;
            re.caseid = model.CaseID;
            re.outrelateid = model.OutRelateID;
            re.elementcontent = new List<MergeElementResultInfo>();
            #endregion
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon();
            #region 处理xml内容
            for (int i = 0; i < model.ElementContent.Count; i++)
            {
                for (int j = 0; j < model.ElementContent[i].Contents.Count; j++)
                {
                    string xmlContent = HttpHelp.DeCodeBase64new(65001, model.ElementContent[i].Contents[j]);
                    xmlContent = XmlNodeAddIDAttribute(xmlContent);
                    model.ElementContent[i].Contents[j] = HttpHelp.EnDataBase64(xmlContent);
                }
            }
            #endregion

            try
            {
                #region 获取案由模板结构
                CaseCauseModel mSYS_Case = sysCaseCause.GetModel(model.CaseCauseID);
                string strxmlTemplate = mSYS_Case.ElementXML;
                XmlDocument xmlDocumentTemplate = new XmlDocument();
                xmlDocumentTemplate.LoadXml(strxmlTemplate);
                #endregion

                #region  获取同节点判定配置
                string xmlpath = @"config/moduleconfig/commonconfig/generalconfig/samenodeconfig/" + model.CaseType + "_" + model.CaseCauseID + ".xml";
                SameNodeConfig xmlConfigModel = LoadXmlSerializableConfig<SameNodeConfig>(xmlpath);
                #endregion

                #region 执行合并
                MultiFactUnion multiFactunion = new MultiFactUnion();
                string kernelfact = string.Empty;
                XmlNode nodetemplate = null;
                foreach (var item in model.ElementContent)
                {
                    MergeElementResultInfo mergeElementResult = new MergeElementResultInfo();
                    mergeElementResult.elementtype = item.ElementType;
                    #region 1.根据要素类型，得到对应的模板
                    switch (item.ElementType)
                    {
                        case 1:
                            nodetemplate = xmlDocumentTemplate.SelectSingleNode("//诉请要素");
                            break;
                        case 2:
                        case 3:
                            nodetemplate = xmlDocumentTemplate.SelectSingleNode("//事实要素");
                            //2.实例合并结果xml
                            XmlDocument confirmdocumenttemp = new XmlDocument();
                            confirmdocumenttemp.LoadXml(string.Format("<{0}></{0}>", nodetemplate.ParentNode.Name));
                            XmlNode xmlNodeFacttConfirm = confirmdocumenttemp.CreateElement("事实要素");
                            confirmdocumenttemp.DocumentElement.AppendChild(xmlNodeFacttConfirm);
                            //3.得到需要合并的第一个Xml，之后用第一个和第二个xml合并，然后用合并后的结果以此再进行合并
                            string firstElement = item.Contents[0];
                            firstElement = HttpHelp.DeCodeBase64new(65001, firstElement);
                            XmlDocument firstD = new XmlDocument();
                            firstD.LoadXml(firstElement);
                            XmlNode lopNode = firstD;
                            for (int i = 1; i < item.Contents.Count; i++)
                            {
                                string mergerOther = HttpHelp.DeCodeBase64new(65001, item.Contents[i]);
                                XmlDocument secondD = new XmlDocument();
                                secondD.LoadXml(mergerOther);
                                xmlNodeFacttConfirm.RemoveAll();
                                multiFactunion.MultiFactUnionXml(nodetemplate, lopNode, secondD, xmlConfigModel.xmllable.ToList(), xmlNodeFacttConfirm, MultiFactBase.SameNodeHandleType.b);
                                //firstD.LoadXml(confirmdocument.OuterXml);
                                lopNode = confirmdocumenttemp.Clone();
                            }
                            //产生缺失要素
                            XmlAttribute facttype = confirmdocumenttemp.CreateAttribute("要素类型");
                            facttype.Value = "4";
                            xmlNodeFacttConfirm.Attributes.Append(facttype);
                            MultiFactKernel factkernel = new MultiFactKernel() { };
                            //赋值案由相关数据
                            factkernel.Ms_caseCauseModeList = new List<CaseCauseModel>() { mSYS_Case };
                            kernelfact = factkernel.MutiBuildKernelFact(nodetemplate, confirmdocumenttemp, true);
                            mergeElementResult.mergeelementresult = HttpHelp.EnDataBase64(confirmdocumenttemp.OuterXml);
                            re.elementcontent.Add(mergeElementResult);
                            break;
                        case 4:
                            XmlDocument kernelDoc = new XmlDocument();
                            if (item.Contents!=null && item.Contents.Any())
                            {
                                List<string> lastNodePaths = new List<string>();
                                if (!string.IsNullOrWhiteSpace(kernelfact))
                                {
                                    //获取缺失要素最子级节点xmlpath
                                    kernelDoc.LoadXml(kernelfact);
                                    List<XmlElement> lastNodes = new List<XmlElement>();
                                    GetLastNodes(kernelDoc.DocumentElement, lastNodes);
                                    if(lastNodes.Any())
                                    {
                                        foreach (var nodeItem in lastNodes)
                                        {
                                            string nodePath = GetXmlPath(nodeItem);
                                            if (!lastNodePaths.Contains(nodePath))
                                                lastNodePaths.Add(nodePath);
                                            else
                                            {
                                                var removeLastNode = kernelDoc.SelectNodes(nodePath);
                                                if(removeLastNode.Count>1)
                                                {
                                                    for (int i = 1; i < removeLastNode.Count; i++)
                                                    {
                                                        removeLastNode[i].ParentNode.RemoveChild(removeLastNode[i]);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                if(lastNodePaths.Any())
                                {
                                    foreach (var rmpathItem in lastNodePaths)
                                    {
                                        bool isRemove = false;
                                        foreach (var objectionItem in item.Contents)
                                        {
                                            string objectionContent = HttpHelp.DeCodeBase64new(65001, objectionItem);
                                            if(!string.IsNullOrWhiteSpace(objectionContent))
                                            {
                                                XmlDocument objectionDoc = new XmlDocument();
                                                objectionDoc.LoadXml(objectionContent);
                                                var objectionNodes = objectionDoc.SelectNodes(rmpathItem);
                                                if (objectionNodes != null && objectionNodes.Count > 0)
                                                {
                                                    isRemove = true;
                                                    break;
                                                }
                                                    
                                            }
                                        }
                                        if(isRemove)
                                        {
                                            var removeNodes = kernelDoc.SelectNodes(rmpathItem);
                                            if(removeNodes!=null && removeNodes.Count>0)
                                            {
                                                for (int i = 0; i < removeNodes.Count; i++)
                                                {
                                                    DeleteNode(removeNodes[i]);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            mergeElementResult.mergeelementresult = HttpHelp.EnDataBase64(kernelDoc.OuterXml);
                            re.elementcontent.Add(mergeElementResult);
                            break;
                    }
                    #endregion

                }
                #endregion
            }
            catch (Exception ex)
            {
                LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, "MergerElement异常" + ex.Message);
            }
            return re;
        }

        /// <summary>
        /// 合并数据接口xml数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string MergerXml(MergeXmlModel model)
        {
            string xmlpath = @"config/moduleconfig/commonconfig/generalconfig/samenodeconfig/" + model.CaseType + "_" + model.CaseCauseID + ".xml";
            SameNodeConfig xmlConfigModel = LoadXmlSerializableConfig<SameNodeConfig>(xmlpath);
            #region 获取案由模板结构
            CaseCauseModel mSYS_Case = sysCaseCause.GetModel(model.CaseCauseID);
            string strxmlTemplate = mSYS_Case.ElementXML;
            XmlDocument xmlDocumentTemplate = new XmlDocument();
            xmlDocumentTemplate.LoadXml(strxmlTemplate);
            #endregion

            MultiFactUnion multiFactunion = new MultiFactUnion();
            XmlNode nodetemplate = null;


            nodetemplate = xmlDocumentTemplate.SelectSingleNode("//事实要素");
            //2.实例合并结果xml
            XmlDocument confirmdocumenttemp = new XmlDocument();
            confirmdocumenttemp.LoadXml(string.Format("<{0}></{0}>", nodetemplate.ParentNode.Name));
            XmlNode xmlNodeFacttConfirm = confirmdocumenttemp.CreateElement("事实要素");
            confirmdocumenttemp.DocumentElement.AppendChild(xmlNodeFacttConfirm);
            //3.得到需要合并的第一个Xml，之后用第一个和第二个xml合并，然后用合并后的结果以此再进行合并
            string firstElement = model.MergerList[0];
            firstElement = HttpHelp.DeCodeBase64new(65001, firstElement);
            XmlDocument firstD = new XmlDocument();
            firstD.LoadXml(firstElement);
            XmlNode lopNode = firstD;
            for (int i = 1; i < model.MergerList.Count; i++)
            {
                string mergerOther = HttpHelp.DeCodeBase64new(65001, model.MergerList[i]);
                XmlDocument secondD = new XmlDocument();
                secondD.LoadXml(mergerOther);
                xmlNodeFacttConfirm.RemoveAll();
                multiFactunion.MultiFactUnionXml(nodetemplate, lopNode, secondD, xmlConfigModel.xmllable.ToList(), xmlNodeFacttConfirm, MultiFactBase.SameNodeHandleType.b);
                lopNode = confirmdocumenttemp.Clone();
            }


            return HttpHelp.EnDataBase64("<案由要素> " +xmlNodeFacttConfirm.OuterXml+ " </案由要素>");
        }


        #region 私有函数
        /// <summary>
        /// 将配置文件序列化为实体对象
        /// </summary>
        /// <param name="xmlpath">配置文件路径</param>
        /// <returns></returns>
        public static T SingleLoadXmlSerializableConfig<T>(string xmlpath)
        {
            // 2020-03-25 gyx 解密配置信息 先根据配置文件路径读出解密后的配置信息，然后将配置信息解析
            string configContent = BllDataHandle.SplitPathThenGetConfigContent(xmlpath);
            Byte[] array = Encoding.UTF8.GetBytes(configContent);
            MemoryStream stream = new MemoryStream(array);
            var type = typeof(T);
            System.Xml.Serialization.XmlSerializer xmlSerializer = System.Xml.Serialization.XmlSerializer.FromTypes(new[] { type }).FirstOrDefault();
            var result = xmlSerializer.Deserialize(stream);
            stream.Dispose();
            return (T)result;
        }

        /// <summary>
        /// 将配置文件序列化为实体对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xmlpath"></param>
        /// <returns></returns>
        protected T LoadXmlSerializableConfig<T>(string xmlpath)
        {
            string configContent = BllDataHandle.SplitPathThenGetConfigContent(xmlpath);
            XmlDocument document = new XmlDocument();
            document.LoadXml(configContent);
            Byte[] array = Encoding.UTF8.GetBytes(document?.OuterXml);
            MemoryStream stream = new MemoryStream(array);
            var type = typeof(T);
            System.Xml.Serialization.XmlSerializer xmlSerializer = System.Xml.Serialization.XmlSerializer.FromTypes(new[] { type }).FirstOrDefault();
            var result = xmlSerializer.Deserialize(stream);
            stream.Dispose();
            return (T)result;
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="text">日志内容</param>
        /// <param name="logType">日志类型</param>
        internal void DoSetLog(string text, LogMessageType logType)
        {
            LogHandle.LogHType log = LogHandle.LogHType.Info;
            foreach (LogHandle.LogHType typ in Enum.GetValues(typeof(LogHandle.LogHType)))
            {
                if (((int)logType) == ((int)typ))
                {
                    log = typ;
                    break;
                }
            }
            //写入记录日志
            LogHandle.GetInitLogHandle.LogWrite(log, "  分人员比对接口： " + text);
        }

        /// <summary>
        /// Xml中的节点添加一个ID属性
        /// </summary>
        /// <param name="xmlContent"></param>
        /// <returns></returns>
        private string XmlNodeAddIDAttribute(string xmlContent)
        {
            XAttribute xAttribute = new XAttribute("id", Snowflake.Instance().GetId().ToString());
            XDocument xdoc = XDocument.Parse(xmlContent);
            if (xdoc.Root.Attribute("id") == null)
                xdoc.Root.Add(xAttribute);
            foreach (var item in xdoc.Root.Elements())
            {
                if (item.Attribute("id") == null)
                    item.Add(xAttribute);
                XmlNodeAddAttribute(item, "id", Snowflake.Instance().GetId().ToString());
            }

            return xdoc.Document.ToString();
        }

        private void XmlNodeAddAttribute(XElement node, string attributeName, string attributeValue)
        {
            XAttribute xAttribute = new XAttribute(attributeName, attributeValue);
            if (node.Attribute(attributeName) == null)
                node.Add(xAttribute);

            foreach (var item in node.Elements())
            {
                XmlNodeAddAttribute(item, attributeName, attributeValue);
            }
        }

        /// <summary>
        /// 获取最下级子节点
        /// </summary>
        private void GetLastNodes(XmlElement root, List<XmlElement> resultNodes)
        {
            foreach (XmlElement item in root.ChildNodes)
            {
                if (!item.HasChildNodes)
                {
                    resultNodes.Add(item);
                }
                else
                {
                    GetLastNodes(item, resultNodes);
                }
            }
        }

        /// <summary>
        /// 根据当前节点，返回xmlpath
        /// </summary>
        protected string GetXmlPath(XmlElement xmlElement)
        {
            try
            {
                string path = "/" + xmlElement.Name;
                XmlNode parent = xmlElement.ParentNode;
                //循环查找节点的父路径直至到顶级无父路径 则为全路径
                while (parent != null && parent != xmlElement.OwnerDocument)
                {
                    path = "/" + parent.Name + path;
                    parent = parent.ParentNode;
                }
                path = path.TrimStart('/');
                return path;
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 删除没有子级的空节点，一直到根节点
        /// </summary>
        /// <param name="removeNode"></param>
        private void DeleteNode(XmlNode removeNode)
        {
            var parentNode = removeNode.ParentNode;
            if(parentNode!=null)
            {
                parentNode.RemoveChild(removeNode);
                if (!parentNode.HasChildNodes)
                    DeleteNode(parentNode);
            }
        }
        #endregion
    }
}
